package com.zyb.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class MyAdvice {
    @Pointcut("execution(String com.zyb.dao.BookDao.findName(..))")
    private void pt() {
    }

    @Before("pt()")
    public void before(JoinPoint jp) {
        Object[] args = jp.getArgs();
        System.out.println(Arrays.toString(args));
        System.out.println("before advice ...");
    }

    @After("pt()")
    public void after(JoinPoint jp) {
        Object[] args = jp.getArgs();
        System.out.println(Arrays.toString(args));
        System.out.println("after advice ...");
    }

    @Around("pt()")
    public Object around1(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("around before advice ...");
        //获取执行签名信息
        Signature signature = pjp.getSignature();
        //通过签名获取执行操作名称(接口名)
        String className = signature.getDeclaringTypeName();
        //通过签名获取执行操作名称(方法名)
        String methodName = signature.getName();
        System.out.println(className+"---->" + methodName);
        Object ret = pjp.proceed();
        System.out.println("around after advice ...");
        return ret;
    }

    @Around("pt()")
    public Object around2(ProceedingJoinPoint pjp) throws Throwable{
        Object[] args = pjp.getArgs();
        System.out.println(Arrays.toString(args));
        args[0]=666;
        Object ret=null;
        try{
            ret = pjp.proceed(args);
        }catch (Throwable e){
            throw new RuntimeException(e);
        }
        System.out.println("around after advice");
        return ret;
    }

    @AfterReturning(value = "pt()",returning = "ret")
    public void afterReturning(JoinPoint jp,String ret) {
        System.out.println("afterReturning advice ..." + ret);
    }

//    @AfterThrowing(value = "pt()",throwing = "t")
//    public void afterThrowing(JoinPoint jp,String t) {
//        System.out.println("afterThrowing advice ..." + t);
//    }
}
